﻿using K3WiseApi.Common;
using K3WiseApi.Dto;
using Kingdee.K3.API.SDK;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace K3WiseApi
{
    public class ApiClient
    {
        public string ApiUrl { get; }
        public string AuthCode { get; }

        public string Token { get; }

        public ApiClient(string apiUrl, string authCode)
        {
            ApiUrl = apiUrl;
            AuthCode = authCode;
            Token = GetToken();

        }

        public string GetToken()
        {
            string apiUrl = ApiUrl;
            string authCode = AuthCode;
            string httpResponse = string.Empty;
            string url = apiUrl + "/Token/Create?authorityCode=" + authCode;
            bool flag = HttpHelper.HttpGet(url, out httpResponse, 6000);
            var apiResult= JsonConvert.DeserializeObject<ApiResult<TokenApiResultDto>>(httpResponse);
            if(apiResult.StatusCode!=Common.StateCode.OK) 
            {
                throw new ApiException(apiResult.Message);
            }
            return apiResult.Data.Token;
        }

        public T HttpPost<T>(string uri,object? postData=null)
        {
            string apiUrl = ApiUrl;
            string authCode = AuthCode;
            string httpResponse = string.Empty;
            string url = apiUrl + $"/{uri}?Token=" + Token;

            byte[] data = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(postData));
            bool flag = HttpHelper.HttpPost(url, data, out httpResponse, 6000);

            var result=JsonConvert.DeserializeObject<ApiResult<T>>(httpResponse);
            if (result.StatusCode != Common.StateCode.OK)
            {
                throw new ApiException(result.Message);
            }
            return result.Data;
        }

        public T HpptGet<T>(string uri,object? data=null)
        {
            string apiUrl = ApiUrl;
            string authCode = AuthCode;
            string httpResponse = string.Empty;
            string url = apiUrl + $"/{uri}?Token=" + Token;
            bool flag = HttpHelper.HttpGet(url, out httpResponse, 6000);
            var result = JsonConvert.DeserializeObject<ApiResult<T>>(httpResponse);
            if (result.StatusCode != Common.StateCode.OK)
            {
                throw new ApiException(result.Message);
            }
            return result.Data;

        }
    }
}
